from django.contrib.auth.models import User
from django.core.management.base import BaseCommand 
from ability.models import Course, Chapter, UserProfile
from os.path import dirname, isfile, join
from os import listdir
import json


class Command(BaseCommand):
  help = 'import student from oracle'

  def handle(self, *args, **options):
      print('handle import points')
      pointdir = dirname(dirname(dirname(dirname(__file__)))) + "/json"
      onlyfiles = [f for f in listdir(pointdir) if isfile(join(pointdir, f))]
      user = UserProfile.objects.filter(username="13800138000").first()
      teacher = user.teacher
      for f in onlyfiles:
        file = join(pointdir, f)
        courseName = f.replace('.json', '')
        course = Course.objects.filter(course_name=courseName).first()
        if course is None:
          course = Course()
          course.course_name = courseName
          course.theo_hours = 60
          course.prac_hours = 60
          course.credit = 5
          course.describe = courseName
          course.status = 'N'
          course.course_type = 'E'
          course.save()
          course.teacher_set.add(teacher)
        with open(file, 'r') as json_file:
          data = json.load(json_file)
          for item in data:
            chapter = Chapter()
            chapter.course = course
            chapter.chapter_name = item['title']
            chapter.detail = item['con']
            chapter.detail_type = 'H'
            chapter.save()

              
